package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.youzan.spiderman.utils.MD5Utils;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.ConnectRequestTipsDialog;
import sz.szsmk.citizencard.model.network.bean.request.SttAuthRequest;
import sz.szsmk.citizencard.model.network.bean.request.SuEXingReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.SttAuthResponse;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.PayPsdInputView;


/**
 * 苏e行授权页面
 *SttAuthActivity
 * */
public class SttAuthActivity extends IBaseActivity {
    private TextView title;
    private LinearLayout progressLayout;
    private NetworkDateSources mNetworkDateSource;
    private NetworkDateSource mNetworkDateSource2;

    private String access_token;
    private ConnectRequestTipsDialog connectRequestTipsDialog;
    private Button auth_btn;

    private LinearLayout ll_mainlayout;
    public void showLoadDialog(String title) {
        if (null == connectRequestTipsDialog) {
            connectRequestTipsDialog = new ConnectRequestTipsDialog();

            Bundle bundle = new Bundle();
            bundle.putString("title",title);
            connectRequestTipsDialog.setArguments(bundle);
        }

        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(connectRequestTipsDialog, this.getClass().getSimpleName());
        ft.commitAllowingStateLoss();
    }

    public void dismissLoadingDialog() {
        if (null != connectRequestTipsDialog) {
            connectRequestTipsDialog.dismissAllowingStateLoss();
            connectRequestTipsDialog = null;
        }

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_sttauth;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        title = (TextView) findViewById(R.id.txt_title);
        auth_btn = (Button)findViewById(R.id.auth_btn);
        ll_mainlayout = (LinearLayout) findViewById(R.id.ll_mainlayout);
        mNetworkDateSource = NetworkDateSources.getInstance();
        mNetworkDateSource2 = NetworkDateSource.getInstance();
        findViewId();
        initData();
        setListener();
    }

    @Override
    protected void updateViews() {

    }





    protected void findViewId() {
        title = (TextView) findViewById(R.id.txt_title);
        auth_btn = (Button)findViewById(R.id.auth_btn);
    }
    private String app_id;
    private String timestamp;
    private String sign;
    private String app_user;

    private String openId;

    protected void initData() {
        title.setText("应用授权(签约代扣)");
        app_id = getIntent().getStringExtra("app_id");
        timestamp = getIntent().getStringExtra("timestamp");
        sign = getIntent().getStringExtra("sign");
        app_user = getIntent().getStringExtra("app_user");


        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(ACache.get(SttAuthActivity.this).getAsString("access_token"));

        mNetworkDateSource.getOpenId(getOpenIdReq, new SubscribeResult<GetOpenIdRes>() {
            @Override
            protected void onOk(GetOpenIdRes response) {
                dismissLoadingDialog();
                openId = response.getOpenId();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                dismissLoadingDialog();
            }
        });

    }


    protected void setListener() {
        auth_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                access_token = ACache.get(SttAuthActivity.this).getAsString("access_token");
                if(TextUtils.isEmpty(access_token)){
                    Bundle bundle = new Bundle();
                    bundle.putInt("stt",1);
                    JumpUtils.jumptoNatvie(SttAuthActivity.this, "login", 0,bundle);
                }else{
                    showInputPwd(ll_mainlayout);
                }
            }
        });
    }
    private PopupWindow popupWindow;

    @SuppressLint("WrongConstant")
    private void showInputPwd(View view) {

            View popView = getLayoutInflater().inflate(
                    R.layout.qr_pop_password, null);
            final PayPsdInputView payPsdInputView = (PayPsdInputView) popView.findViewById(R.id.password);
            TextView tv_qr_cancel = (TextView) popView.findViewById(R.id.tv_qr_cancel);
            TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
            popupWindow = new PopupWindow(popView,
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.
            popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
            popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(true); //点击外部关闭。
            popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
            backgroundAlpha(0.5f);
            //设置Gravity，让它显示在右上角。

            popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);


            tv_qr_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });

            tv_qr_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String password = payPsdInputView.getPasswordString();
                    if (password.length() < 6) {
                        showTipDialog("密码位数不全");
                    } else {
                        showLoadingDialog();
                        SuEXingReq suEXingReq = new SuEXingReq();
                        String randomStr =  System.currentTimeMillis()+"";
                        suEXingReq.setNonce(randomStr);
                        suEXingReq.setPassWord(password);
                        suEXingReq.setSignature(MD5Utils.getStringMd5(randomStr+"75e875006d896336"));      //随机数  + key 值   然后 MD5加密
                        suEXingReq.setOpenId(openId);

                        checkPwdSeX(suEXingReq);
                    }
                }
            });

            popupWindow.setOnDismissListener(new poponDismissListener());
    }

    private void checkPwdSeX(SuEXingReq suEXingReq) {
        mNetworkDateSource2.checkPwdForSeX(suEXingReq, new SubscribeResult<BaseBean>() {
            @Override
            protected void onOk(BaseBean response) {
                Log.d("log", "onOk: ");
                popupWindow.dismiss();
                auth();
                showLoadDialog("正在授权...");
            }

            @Override
            protected void onFailure(BaseBean response) {
                super.onFailure(response);
                dismissLoadingDialog();
                Toast.makeText(SttAuthActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(popupWindow!=null){
            popupWindow.dismiss();
        }
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    private void showTipDialog(String tip) {
        PubUtils.popTipOrWarn(this, tip);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }
    }

    private void auth() {

        SttAuthRequest sttAuthRequest = new SttAuthRequest();
        sttAuthRequest.setAccess_token(access_token);//7172d58ccbb612ad32e0b43fab0a8c1c
        sttAuthRequest.setApp_id(app_id);
        sttAuthRequest.setApp_user(app_user);
        sttAuthRequest.setSign(sign);
        sttAuthRequest.setTimestamp(timestamp);
        sttAuthRequest.setTag("METRO");
        String json = new Gson().toJson(sttAuthRequest);

        mNetworkDateSource.sttAuth(sttAuthRequest, new SubscribeResult<SttAuthResponse>() {
            @Override
            protected void onOk(SttAuthResponse response) {

                dismissLoadingDialog();
                String json = new Gson().toJson(response);
                Intent i = new Intent();
                i.putExtra("authResp", json);
                setResult(RESULT_OK,i);
                finish();
            }

            @Override
            protected void onFailure(SttAuthResponse response) {
                super.onFailure(response);


                dismissLoadingDialog();
                if("1002".equals(response.getCode())){
                    Toast.makeText(SttAuthActivity.this,"登录失效，请重新登录",Toast.LENGTH_LONG).show();
                    Bundle bundle = new Bundle();
                    bundle.putInt("stt",1);
                    JumpUtils.jumptoNatvie(SttAuthActivity.this, "login", 0,bundle);
                }else{
                    String json = new Gson().toJson(response);
                    Intent i = new Intent();
                    i.putExtra("authResp", json);
                    setResult(RESULT_OK ,i);
                    finish();
                }

//                ((IPowerContract.IPowerView) mView).checkOrderFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                dismissLoadingDialog();
            }
        });

    }



}
